import Vue from "vue"
import Vuex from "vuex"
import Api from "@/api/api.js"
import utils from "@/utils/utils.js"
const localUserData = sessionStorage.getItem("vod-user-data")?JSON.parse(sessionStorage.getItem("vod-user-data")):{};
Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
    isDebug: location.hostname=="localhost"?true:false,
    baseHost: localStorage.getItem("vod-hostname")?localStorage.getItem("vod-hostname"):'https://car-eye.cn:5001',//(location.protocol+"//"+location.host),
    userData: localUserData,//用户信息
    currentFirstMenuIndex: null,
    commentData: {//公共变量
      deptCarList: [],//所有的机构车辆数组
    },
    alertDuration: 2500
  },
  mutations: {
    loginOutInitData(state){
      state.userData = {};
      sessionStorage.removeItem("vod-user-data");
    },
    setUserData(state,data){
      state.userData = data;
      sessionStorage.setItem("vod-user-data",JSON.stringify(data));
    },
    setCurrentFirstMenuIndex(state,index){
      state.currentFirstMenuIndex = index;
    },
    setDeptCarData(state,list){
      state.commentData.deptCarList = list;
    },
  },
  actions:{
    loginOutInitData(context){
      context.commit('loginOutInitData');
    },
    setUserData(context,data){
      context.commit('setUserData',data);
    },
    setCurrentFirstMenuIndex(context,index){
      context.commit('setCurrentFirstMenuIndex',index);
    },
    setDeptCarData(context,callback){//获取树
      Api.getData("/v3/config/group",{}).then(function(res){//获取所有树级关系
        if(res.tree&&res.tree.children&&res.tree.children.length>0){
          function loop(arr,parent){
            for (let i = 0; i < arr.length; i++) {
              arr[i].parentId = parent.nodeId;
              arr[i].parentName = parent.name;
              arr[i].nodeId = utils.randomStr(16);//因为返回的id有可能会出现重复
              if(arr[i].group){//是分组
                arr[i].nodetype = 1;
                arr[i].isParent = true;
                if(arr[i].children){
                  loop(arr[i].children,arr[i]);
                }
              }else{//是通道 
                arr[i].status = arr[i].status=="ON"?2:1;
                arr[i].iconSkin = "treeIconChannel"+arr[i].status;
                //这里会覆盖掉之前nodetype=1的定义
                parent.nodetype = 2;
                parent.iconSkin = "treeIconDevice";
              }
            }
          }
          loop(res.tree.children,{nodeId:"all-1",name:"所有设备"});
          let resList = [{
            parentId:"",
            id:"all-1",
            nodeId:"all-1",
            nodetype:1,//,1机构，2设备，空通道
            name:"所有设备",
            children:res.tree.children
          }];
          console.log(JSON.parse(JSON.stringify(resList)))
          context.commit('setDeptCarData',resList);
          if(callback)callback();
        }
      }).catch(function(err){
        console.log(err);
      });
    },
  }
})
export default store;